package me.hekr.iotos.softgateway.subsystem.service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import me.hekr.iotos.softgateway.common.utils.ThreadPoolUtil;
import me.hekr.iotos.softgateway.core.klink.KlinkService;
import me.hekr.iotos.softgateway.core.klink.ModelData;
import me.hekr.iotos.softgateway.core.listener.DeviceRemoteConfigListenerAdapter;
import me.hekr.iotos.softgateway.subsystem.dto.RadioDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** @author iotos */
@Service
public class SubsystemService extends DeviceRemoteConfigListenerAdapter {
  @Autowired private KlinkService klinkService;
  @Autowired private UdpServerService udpServerService;

  @Override
  public void firstAfter() {
    // 监听到远程配置准备好了，进行业务初始化
    init();
  }

  private void init() {
    ThreadPoolUtil.DEFAULT_SCHEDULED.scheduleWithFixedDelay(
        this::syncDevices, 0, 60, TimeUnit.SECONDS);
  }

  public void syncDevices() {
    List<RadioDevice> devices = udpServerService.getAllStatus();

    for (RadioDevice d : devices) {

      // 如果是离线，设置iot的设备离线
      if (d.getStatus() == 0) {
        klinkService.devLogout(d);
        continue;
      }

      ModelData data =
          ModelData.cmd("report").param("vol", d.getVol()).param("playStat", d.getPlayStat());
      klinkService.devSend(d, data);
    }
  }
}
